package com.blogs.ui;

import java.io.File;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blogs.component.BaseActivity;
import com.blogs.component.DownloadProgressListener;
import com.blogs.tools.FileDownloader;
import com.cnblogs.R;

public class VersionUpdateActivity extends BaseActivity implements OnClickListener{
	private TextView title_include_title;
	private Button title_include_back;
	private TextView version_text_tv;
	private TextView version_introduction_tv;
	private Button version_update_btn;
	private Button version_install_btn;
	private ProgressBar version_update_pb;
	
	private String file_path;
	private String fileName="Cnblogs.apk";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.version_update);
		ViewGroup headview=(ViewGroup)findViewById(R.id.main_title_include);
		title_include_title=(TextView)headview.findViewById(R.id.title_include_title);
		title_include_back=(Button)headview.findViewById(R.id.title_include_back);
		title_include_title.setText("版本更新");
		title_include_back.setVisibility(View.VISIBLE);
		title_include_back.setOnClickListener(this);
		
		version_text_tv=(TextView)findViewById(R.id.version_text_tv);
		version_introduction_tv=(TextView)findViewById(R.id.version_introduction_tv);
		version_update_btn=(Button)findViewById(R.id.version_update_btn);
		version_install_btn=(Button)findViewById(R.id.version_install_btn);
		version_update_pb=(ProgressBar)findViewById(R.id.version_update_pb);
		String version_text=getIntent().getStringExtra("version_text");
		String version_introduction=getIntent().getStringExtra("version_introduction");
		file_path=getIntent().getStringExtra("file_path");
		version_text_tv.setText(version_text);
		version_introduction_tv.setText(version_introduction);
		version_update_btn.setOnClickListener(this);
		version_install_btn.setOnClickListener(this);
	}
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v==title_include_back)
		{
			finish();
		}
		else if(v==version_update_btn)
		{
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				version_update_btn.setClickable(false);
                download(file_path, Environment.getExternalStorageDirectory());
            }else{
                Toast.makeText(VersionUpdateActivity.this, "SDCard不存在或者写保护", 1).show();
            }
		}
		else if(v==version_install_btn)
		{
			 Intent install_intent = new Intent();
			 install_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			 install_intent.setAction(android.content.Intent.ACTION_VIEW);
			 install_intent.setDataAndType(Uri.fromFile(new File( Environment.getExternalStorageDirectory()+"/"+fileName)),
                     "application/vnd.android.package-archive");
             startActivity(install_intent);
		}
	}
    /**
     * 主线程(UI线程)
     * 对于显示控件的界面更新只是由UI线程负责，如果是在非UI线程更新控件的属性值，更新后的显示界面不会反映到屏幕上
     * @param path
     * @param savedir
     */
	private void download(final String path, final File savedir) {
        new Thread(new Runnable() {         
        	public void run() {
        		// TODO Auto-generated method stub
        		FileDownloader loader = new FileDownloader(VersionUpdateActivity.this, path, savedir,fileName, 3);
        		version_update_pb.setMax(loader.getFileSize());//设置进度条的最大刻度为文件的长度
        		try {
                    loader.download(new DownloadProgressListener() {
                    	public void onDownloadSize(int size) {
                    		// TODO Auto-generated method stub
                    		//实时获知文件已经下载的数据长度
                    		Message msg = new Message();
                            msg.what = 1;
                            msg.getData().putInt("size", size);
                            handler.sendMessage(msg);//发送消息
                    	}
                    });
                } catch (Exception e) {
                	 handler.obtainMessage(-1).sendToTarget();
                }
        	}
        }).start();
	}
	
	 /**
     * 当Handler被创建会关联到创建它的当前线程的消息队列，该类用于往消息队列发送消息
     * 消息队列中的消息由当前线程内部进行处理
     */
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {            
            switch (msg.what) {
            case 1:                
            	version_update_pb.setProgress(msg.getData().getInt("size"));
                float num = (float)version_update_pb.getProgress()/(float)version_update_pb.getMax();
                int result = (int)(num*100);
                version_update_btn.setText(result+ "%");
                
                if(version_update_pb.getProgress()==version_update_pb.getMax()){
                    Toast.makeText(VersionUpdateActivity.this,"下载完成", 1).show();
                    version_update_pb.setVisibility(View.GONE);
                    version_update_btn.setVisibility(View.GONE);
                    version_install_btn.setVisibility(View.VISIBLE);
                }
                break;
            case -1:
                Toast.makeText(VersionUpdateActivity.this,"下载失败", 1).show();
                break;
            }
        }
    };
	
}
